package com.example.cart;

import static com.example.cart.utils.GoodsDetailUtil.renderGoodsUnit;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.cart.dto.Cart;
import com.example.cart.dto.Goods;
import com.example.cart.repository.CartDao;
import com.example.cart.repository.GoodsDao;

import java.util.List;

public class GoodsDetailActivity extends AppCompatActivity {

    private CartDao cartDao;
    private int goodsId;
    private TextView cartCountView;
    //private View goodsDetailUnit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_goods_detail);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        goodsId = getIntent().getIntExtra("goods_id",0);

        if (goodsId ==0) {
            return;
        }

        cartDao = CartApplication.get().getGoodsDataBase().cartDao();

        findViewById(R.id.addToCart).setOnClickListener(view->{

            Cart cartInDb = cartDao.queryById(goodsId);
            Cart cart = new Cart();
            cart.setGoodsId(goodsId);
            if (cartInDb==null) {
                cart.setQuantity(1);
                cartDao.insert(cart);
            }else{
                cart.setId(cartInDb.getId());
                cart.setQuantity(cartInDb.getQuantity()+1);
                cartDao.Update(cart);
            }



            CartApplication.get().refreshCartCount();

            Toast.makeText(this,"成功添加到购物车",Toast.LENGTH_SHORT).show();
        });

        //goodsDetailUnit = findViewById(R.id.goodsDetailUnit);

        loadData();


        findViewById(R.id.goBack).setOnClickListener(view->{
            finish();
        });

        findViewById(R.id.goToCart).setOnClickListener(view->{

            startActivity(new Intent(this,CartActivity.class));

        });

        cartCountView = findViewById(R.id.cartCount);

    }



    private void loadData() {
        Goods goods = CartApplication.get().getGoodsDataBase().goodsDao().queryById(goodsId);

        renderGoodsUnit(goods, findViewById(R.id.main));
    }

    @Override
    protected void onResume() {
        super.onResume();

        cartCountView.setText(String.valueOf(CartApplication.get().getCartCount()));
    }
}